#!/bin/bash
### BEGIN INIT INFO
# Provides:          tempToGoogle
# Required-Start:    $remote_fs $syslog
# Required-Stop:     $remote_fs $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# Short-Description: controls tempToGoogle
# Description:       This file should be used to start , stat, restart, stop
#                    the tempToGoogle service. 
#                    placed in /etc/init.d.
### END INIT INFO

## sudo cp this file into /etc/init.d/tempToGoogled
## chmod 755
## ex usage: sudo service tempToGoogled stop
## tempToGoogle daemon
## chkconfig: 345 20 80
## description: tempToGoogle daemon
## processname: tempToGoogle

DAEMON_PATH="/home/pi/projects/swautomation/"

DAEMON="python tempToGoogle.py"
DAEMONOPTS=""

NAME=tempToGoogled
DESC="tempToGoogle records data & writes it to Google spreadsheets"
PIDFILE=/var/run/$NAME.pid
SCRIPTNAME=/etc/init.d/$NAME
STATUS_RESULT=1

do_status()
{
   printf "%-50s" "Checking $NAME..."
   if [ -f $PIDFILE ]; then
      PID=`cat $PIDFILE`
      if [ -z "`ps axf | grep ${PID} | grep -v grep`" ]; then
         printf "\n%s\n" "Process dead but pidfile exists, removing..."
         rm -f $PIDFILE
         STATUS_RESULT=0
      else
         echo "Running"
         STATUS_RESULT=1
      fi
   else
      printf "%s\n" "Service not running"
      STATUS_RESULT=0
   fi
   printf "%s\n" "status = $STATUS_RESULT "
}

do_stop()
{
   printf "%-50s" "Stopping $NAME"
   PID=`cat $PIDFILE`
   cd $DAEMON_PATH
   if [ -f $PIDFILE ]; then
##      kill -HUP $PID
      kill -TERM $PID
      printf "%s\n" "Ok"
      rm -f $PIDFILE
   else
      printf "%s\n" "pidfile not found"
   fi

}

do_start()
{
   do_status
   # check if status returns 0
   if [ "$STATUS_RESULT" -eq "1" ]; then
      echo -n "Already running !"
      echo
   else
      printf "%-50s" "Starting $NAME..."
      cd $DAEMON_PATH
      PID=`$DAEMON $DAEMONOPTS > /dev/null 2>&1 & echo $!`
      #echo "Saving PID" $PID " to " $PIDFILE
      if [ -z $PID ]; then
          printf "%s\n" "Fail"
      else
          echo $PID > $PIDFILE
          printf "%s\n" "Ok"
      fi
   fi

}

case "$1" in
start)
   do_start
;;
status)
   do_status
;;
stop)
   do_stop
;;

restart)
  	do_stop
  	do_start
;;

*)
        echo "Usage: $0 {status|start|stop|restart}"
        exit 1
esac
